package br.com.pattern.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public abstract class GenericDao {

	private ConnectionDataBaseGeneric connectionDataBaseGeneric;

	protected GenericDao(ConnectionDataBaseGeneric connectionDataBaseGeneric) {
		this.connectionDataBaseGeneric = connectionDataBaseGeneric;
	}		

	protected Connection getConnection() {
		
		if(connectionDataBaseGeneric.connection == null){
			return connectionDataBaseGeneric.getConnection();
		}
		else{
			return connectionDataBaseGeneric.connection;
		}
	}
	
	public void setConnectionDataBaseGeneric(ConnectionDataBaseGeneric connectionDataBaseGeneric) {
		this.connectionDataBaseGeneric = connectionDataBaseGeneric;
	}

	protected void save(String insertSql, Object... parametros) {

		try{

			PreparedStatement pstmt = getConnection().prepareStatement(insertSql);

			for (int i = 0; i < parametros.length; i++) {
				pstmt.setObject(i+1, parametros[i]);
			}

			pstmt.execute();
			pstmt.close();

		}catch(SQLException e){
			e.printStackTrace();
		}

	}

	protected void update(String updateSql, Object id, Object... parametros) {

		try{
			PreparedStatement pstmt = getConnection().prepareStatement(updateSql);

			for (int i = 0; i < parametros.length; i++) {
				pstmt.setObject(i+1, parametros[i]);
			}

			pstmt.setObject(parametros.length + 1, id);

			pstmt.execute();
			pstmt.close();

		}catch(SQLException e){
			e.printStackTrace();
		}

	}

	protected void delete(String deleteSql, Object... parametros){

		try{
			PreparedStatement pstmt = getConnection().prepareStatement(deleteSql);

			for (int i = 0; i < parametros.length; i++) {
				pstmt.setObject(i+1, parametros[i]);
			}	 

			pstmt.execute();	 
			pstmt.close();

		}catch(SQLException e){
			e.printStackTrace();
		}

	}

}
